package com.snda.lib.util;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.text.DecimalFormat;
import android.content.Context;
import android.os.Environment;
import android.util.Log;

public class FileHelper {

	public static final String NO_CACHE_PATH = "/.nomedia";

	public static long getFileSize(String strFileName) {
		if (FileHelper.isExistFile(strFileName) == false)
			return 0;

		try {
			FileInputStream fis = new FileInputStream(strFileName);
			return fis.available();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}

		return 0;
	}

	/**
	 * 新建目录
	 * 
	 * @param folderPath
	 *            String 如 c:/fqf
	 * @return boolean
	 */
	public static void newFolder(String folderPath) {
		try {
			String filePath = folderPath;
			filePath = filePath.toString();
			java.io.File myFilePath = new java.io.File(filePath);
			if (!myFilePath.exists()) {
				myFilePath.mkdir();
			}
		} catch (Exception e) {
			System.out.println("新建目录操作出错");
			e.printStackTrace();
		}
	}

	/**
	 * 新建文件
	 * 
	 * @param filePathAndName
	 *            String 文件路径及名称 如c:/fqf.txt
	 * @param fileContent
	 *            String 文件内容
	 * @return boolean
	 */
	public static void newFile(String filePathAndName, String fileContent) {

		try {
			String filePath = filePathAndName;
			filePath = filePath.toString();
			File myFilePath = new File(filePath);
			if (!myFilePath.exists()) {
				myFilePath.createNewFile();
			}
			FileWriter resultFile = new FileWriter(myFilePath);
			PrintWriter myFile = new PrintWriter(resultFile);
			String strContent = fileContent;
			myFile.println(strContent);
			resultFile.close();

		} catch (Exception e) {
			System.out.println("新建目录操作出错");
			e.printStackTrace();
		}
	}

	/**
	 * 删除文件
	 * 
	 * @param filePathAndName
	 *            String 文件路径及名称 如c:/fqf.txt
	 * @param fileContent
	 *            String
	 * @return boolean
	 */
	public static void delFile(String filePathAndName) {
		try {
			String filePath = filePathAndName;
			filePath = filePath.toString();
			java.io.File myDelFile = new java.io.File(filePath);
			myDelFile.delete();

		} catch (Exception e) {
			System.out.println("删除文件操作出错");
			e.printStackTrace();
		}
	}

	/**
	 * 删除文件夹
	 * 
	 * @param filePathAndName
	 *            String 文件夹路径及名称 如c:/fqf
	 * @param fileContent
	 *            String
	 * @return boolean
	 */
	public static void delFolder(String folderPath) {
		try {
			delAllFile(folderPath); // 删除完里面所有内容
			String filePath = folderPath;
			filePath = filePath.toString();
			java.io.File myFilePath = new java.io.File(filePath);
			myFilePath.delete(); // 删除空文件夹

		} catch (Exception e) {
			System.out.println("删除文件夹操作出错");
			e.printStackTrace();
		}
	}

	/**
	 * 删除文件夹里面的所有文件
	 * 
	 * @param path
	 *            String 文件夹路径 如 c:/fqf
	 */
	public static void delAllFile(String path) {
		File file = new File(path);
		if (!file.exists()) {
			return;
		}
		if (!file.isDirectory()) {
			return;
		}
		String[] tempList = file.list();
		File temp = null;
		for (int i = 0; i < tempList.length; i++) {
			if (path.endsWith(File.separator)) {
				temp = new File(path + tempList[i]);
			} else {
				temp = new File(path + File.separator + tempList[i]);
			}
			if (temp.isFile()) {
				temp.delete();
			}
			if (temp.isDirectory()) {
				delAllFile(path + "/" + tempList[i]);// 先删除文件夹里面的文件
				delFolder(path + "/" + tempList[i]);// 再删除空文件夹
			}
		}
	}

	/**
	 * 复制单个文件
	 * 
	 * @param oldPath
	 *            String 原文件路径 如：c:/fqf.txt
	 * @param newPath
	 *            String 复制后路径 如：f:/fqf.txt
	 * @return boolean
	 */
	public static void copyFile(String oldPath, String newPath) {
		try {
			int bytesum = 0;
			int byteread = 0;
			File oldfile = new File(oldPath);
			if (oldfile.exists()) { // 文件存在时
				InputStream inStream = new FileInputStream(oldPath); // 读入原文件
				FileOutputStream fs = new FileOutputStream(newPath);
				byte[] buffer = new byte[1444];

				while ((byteread = inStream.read(buffer)) != -1) {
					bytesum += byteread; // 字节数 文件大小
					System.out.println(bytesum);
					fs.write(buffer, 0, byteread);
				}
				inStream.close();
			}
		} catch (Exception e) {
			System.out.println("复制单个文件操作出错");
			e.printStackTrace();

		}

	}

	/**
	 * 复制整个文件夹内容
	 * 
	 * @param oldPath
	 *            String 原文件路径 如：c:/fqf
	 * @param newPath
	 *            String 复制后路径 如：f:/fqf/ff
	 * @return boolean
	 */
	public static void copyFolder(String oldPath, String newPath) {

		try {
			(new File(newPath)).mkdirs(); // 如果文件夹不存在 则建立新文件夹
			File a = new File(oldPath);
			String[] file = a.list();
			File temp = null;
			for (int i = 0; i < file.length; i++) {
				if (oldPath.endsWith(File.separator)) {
					temp = new File(oldPath + file[i]);
				} else {
					temp = new File(oldPath + File.separator + file[i]);
				}

				if (temp.isFile()) {
					FileInputStream input = new FileInputStream(temp);
					FileOutputStream output = new FileOutputStream(newPath
							+ "/" + (temp.getName()).toString());
					byte[] b = new byte[1024 * 5];
					int len;
					while ((len = input.read(b)) != -1) {
						output.write(b, 0, len);
					}
					output.flush();
					output.close();
					input.close();
				}
				if (temp.isDirectory()) {// 如果是子文件夹
					copyFolder(oldPath + "/" + file[i], newPath + "/" + file[i]);
				}
			}
		} catch (Exception e) {
			System.out.println("复制整个文件夹内容操作出错");
			e.printStackTrace();

		}

	}

	/**
	 * 移动文件到指定目录
	 * 
	 * @param oldPath
	 *            String 如：c:/fqf.txt
	 * @param newPath
	 *            String 如：d:/fqf.txt
	 */
	public static void moveFile(String oldPath, String newPath) {
		copyFile(oldPath, newPath);
		delFile(oldPath);

	}

	/**
	 * 移动文件到指定目录
	 * 
	 * @param oldPath
	 *            String 如：c:/fqf.txt
	 * @param newPath
	 *            String 如：d:/fqf.txt
	 */
	public static void moveFolder(String oldPath, String newPath) {
		copyFolder(oldPath, newPath);
		delFolder(oldPath);

	}

	/**
	 * 检查给定的文件路径是否存在
	 * 
	 * @param strFile
	 * @return
	 */
	public static boolean isExistFile(String strFile) {
		if (strFile == null)
			return false;

		File f = new File(strFile);
		return f.exists();
	}

	/**
	 * 判断手机SD卡中是否有指定的文件
	 * 
	 * @param context
	 * @param filename
	 * @return
	 */
	public static boolean judgeFileExist(Context context, String path,
			String filename) {
		File dir = new File(path);
		if (!dir.exists())
			dir.mkdirs();
		File file = new File(dir, filename);
		return file.exists();
	}

	/**
	 * 将给定的文件大小格式化为10K,10M这种格式
	 * 
	 * @param bytesize
	 * @return
	 */
	public static String getSizeDesc(long bytesize) {
		double kbSize = bytesize / 1024.0;
		if (kbSize < 1024.0) {
			DecimalFormat df = new DecimalFormat("####");
			return df.format(kbSize) + "KB";
		}
		double mbSize = kbSize / 1024.0;
		DecimalFormat df = new DecimalFormat("####.0");
		return df.format(mbSize) + "MB";
	}

	/**
	 * 对给定的文件名称进行缩略
	 * 
	 * @param filename
	 * @return
	 */
	public static String getShortFileName(String strFileName) {
		int maxLen = 15;
		int p = strFileName.lastIndexOf('.');
		String ext = strFileName.substring(p);
		String name = strFileName.substring(0, p);
		if (name.length() <= maxLen) {
			return strFileName;
		}

		return name.substring(0, 7) + "..." + name.substring(name.length() - 5)
				+ ext;
	}

	/**
	 * 对给定的文件名称进行缩略
	 * 
	 * @param filename
	 * @return
	 */
	public static String getShortFileName(String strFileName, int nMaxLength) {
		if (strFileName.length() <= nMaxLength) {
			return strFileName;
		}

		String strName = strFileName.substring(0, nMaxLength);
		strName += "...";
		return strName;
	}

	public static File saveImageToDisk(Context context,
			InputStream bmInputStream, String fileName) throws FileException {

		File imageFileOnExternalDirectory = null;

		try {
			String storageState = Environment.getExternalStorageState();
			if (storageState.contains("mounted")) {
				File savePath = new File(LibSettings.getImagePath(context));

				if (!savePath.exists()) {
					File datingBarDirectory = new File(
							LibSettings.getLibPath(context));
					datingBarDirectory.mkdir();
					File datingBarImageDirectory = new File(
							LibSettings.getImagePath(context));
					datingBarImageDirectory.mkdir();

					// issue #30 : insert the .nomedia file so that the
					// won't be parsed by other photo apps
					File noMediaFile = new File(
							LibSettings.getImagePath(context) + NO_CACHE_PATH);
					if (!noMediaFile.createNewFile()) {
						if (!noMediaFile.createNewFile()) {
							throw new FileException("no sdcard");
						}
					}
				}

				imageFileOnExternalDirectory = new File(savePath, fileName);
			} else {
				throw new FileException("no sdcard");
			}

			FileOutputStream fos;
			fos = new FileOutputStream(imageFileOnExternalDirectory);
			byte[] buf = new byte[1024];
			int len;
			while ((len = bmInputStream.read(buf)) > 0) {
				fos.write(buf, 0, len);
			}
			fos.close();
			bmInputStream.close();

		} catch (FileNotFoundException e) {
			throw new FileException(e.getMessage());
		} catch (IOException e) {
			throw new FileException(e.getMessage());
		}

		return imageFileOnExternalDirectory;
	}

	/*
	 * 根据给定的路径和文件名写入到SD卡中
	 */
	public static File getFilePathInSD(Context context, String strSavePath,
			String strFileName) {

		if (strFileName == null)
			return null;

		// 剔除名称中的?
		int nIndex = strFileName.indexOf('?');
		if (nIndex != -1) {
			strFileName = strFileName.substring(0, nIndex);
			if (strFileName == null)
				return null;
		}

		File saveFile = new File(strSavePath + "/" + strFileName);
		if (saveFile.exists() == true)
			return saveFile;

		boolean bCreate = false;
		try {

			saveFile.getParentFile().mkdir();
			bCreate = saveFile.createNewFile();
			if (bCreate == true) {
				return saveFile;
			} else {
				return null;
			}

		} catch (IOException e1) {
			return null;
		}
	}

	/*
	 * 根据给定的路径和文件名写入到手机内存中
	 */
	public static File getFilePathInMem(Context context, String strFileName) {

		if (strFileName == null)
			return null;

		// 剔除名称中的?
		int nIndex = strFileName.indexOf('?');
		if (nIndex != -1) {
			strFileName = strFileName.substring(0, nIndex);
			if (strFileName == null)
				return null;
		}

		try {
			FileOutputStream fos = context.openFileOutput(strFileName,
					Context.MODE_WORLD_READABLE);
			if (fos != null)
				return context.getFileStreamPath(strFileName);

		} catch (FileNotFoundException e) {
			return null;
		}

		return null;
	}

	/*
	 * 根据给定的路径和文件名获取写入的文件流，策略如下
	 * 
	 * 1、如果strSavePath为null，则直接写入到data/data/xxxx/files目录下下
	 * 2、如果是写入到SDCard目录中，则优先写入
	 * 3、如果需要写入到SDCard目录下，但是没有SDCard，则写入到/data/data/xxxx/files目录下
	 * 
	 * @param strSavePath 写入的路径
	 * 
	 * @param strFileName 写入的文件名
	 * 
	 * @param bContinue 是否追加文件
	 */
	public static FileOutputStream getOutputFileStream(Context context,
			String strSavePath, String strFileName, boolean bContinue,
			StringBuffer strResultOutPath) {

		FileOutputStream fos = null;

		// SD卡
		File sdFile = getFilePathInSD(context, strSavePath, strFileName);
		if (sdFile != null) {
			try {
				if (bContinue == true) {
					fos = new FileOutputStream(sdFile, true);
				} else {
					fos = new FileOutputStream(sdFile);
				}
			} catch (FileNotFoundException e) {
				return null;
			}

			strResultOutPath.append(sdFile.getAbsolutePath());
			return fos;
		}

		File memFile = getFilePathInMem(context, strFileName);
		if (memFile != null) {

			try {
				if (bContinue == true) {
					fos = context.openFileOutput(strFileName,
							Context.MODE_APPEND + Context.MODE_WORLD_READABLE);
				} else {
					fos = context.openFileOutput(strFileName,
							Context.MODE_WORLD_READABLE);

				}
			} catch (FileNotFoundException e) {
				return null;
			}

			strResultOutPath.append(memFile.getAbsolutePath());
			return fos;
		}

		return null;
	}

	/*
	 * 根据给定的路径和文件名获取写入的文件流，策略如下
	 */
	public static FileInputStream getInputFileStream(Context context,
			String strSavePath, String strFileName) {

		if (strFileName == null)
			return null;

		int nIndex = strFileName.indexOf('?');
		if (nIndex != -1) {
			strFileName = strFileName.substring(0, nIndex);
			if (strFileName == null)
				return null;
		}

		FileInputStream fis = null;

		// SD卡
		File sdFile = getFilePathInSD(context, strSavePath, strFileName);
		if (sdFile != null) {

			try {
				fis = new FileInputStream(sdFile.getAbsoluteFile());
			} catch (FileNotFoundException e) {
				// 失败
			}

			return fis;
		}

		try {
			fis = context.openFileInput(strFileName);
		} catch (FileNotFoundException e) {
			return null;
		}

		return fis;
	}

	public static int getExistFileSize(Context context, String strSavePath,
			String strFileName) {

		if (strFileName == null)
			return 0;

		int nIndex = strFileName.indexOf('?');
		if (nIndex != -1) {
			strFileName = strFileName.substring(0, nIndex);
			if (strFileName == null)
				return 0;
		}

		FileInputStream fis = FileHelper.getInputStream(context, strSavePath,
				strFileName);

		if (fis != null) {
			try {
				return fis.available();
			} catch (IOException e) {
			}
		}

		return 0;
	}

	/*
	 * 根据给定的路径和文件名获取写入的文件流，策略如下
	 * 
	 * 1、如果strSavePath为null，则直接写入到data/data/xxxx/files目录下下
	 * 2、如果是写入到SDCard目录中，则优先写入
	 * 3、如果需要写入到SDCard目录下，但是没有SDCard，则写入到/data/data/xxxx/files目录下
	 * 
	 * @param strSavePath 写入的路径
	 * 
	 * @param strFileName 写入的文件名
	 * 
	 * @param bContinue 是否追加文件
	 */
	public static FileOutputStream getOutputStream(Context context,
			String strSavePath, String strFileName, boolean bContinue,
			StringBuffer strFilePath) {

		if (strFileName == null)
			return null;

		int nIndex = strFileName.indexOf('?');
		if (nIndex != -1) {
			strFileName = strFileName.substring(0, nIndex);
			if (strFileName == null)
				return null;
		}

		strFilePath.delete(0, strFilePath.length());

		// 以追加方式进行写入
		FileOutputStream fos = null;

		// strSavePath 为nul
		if (strSavePath == null) {
			if (context == null)
				return null;

			try {
				if (bContinue == true) {
					fos = context.openFileOutput(strFileName,
							Context.MODE_WORLD_READABLE);
				} else {
					fos = context.openFileOutput(strFileName,
							Context.MODE_WORLD_READABLE);
				}

				strFilePath.append(context.getFilesDir() + "/" + strFileName);
			} catch (FileNotFoundException e) {
				return null;
			}

			return fos;
		}

		// 创建文件失败
		File saveFile = new File(strSavePath + "/" + strFileName);
		boolean bCreate = false;
		try {
			if (saveFile.exists() == true) {
				bCreate = true;
			} else {
				saveFile.getParentFile().mkdir();
				bCreate = saveFile.createNewFile();
			}
		} catch (IOException e1) {
			Log.d("TYLib", e1.getMessage());
		}

		if (bCreate == true) {

			// 如果strSavePath不为空，则保存到指定的文件中
			try {
				if (bContinue == true) {
					fos = new FileOutputStream(strSavePath + "/" + strFileName,
							true);
				} else {
					fos = new FileOutputStream(strSavePath + "/" + strFileName);
				}

				strFilePath.append(strSavePath + "/" + strFileName);
			} catch (FileNotFoundException e) {
				// 失败
			}
			if (fos != null)
				return fos;
		}

		if (context == null)
			return null;

		try {
			if (bContinue == true) {
				fos = context.openFileOutput(strFileName, Context.MODE_APPEND
						+ Context.MODE_WORLD_READABLE);
			} else {
				fos = context.openFileOutput(strFileName,
						Context.MODE_WORLD_READABLE);

			}
		} catch (FileNotFoundException e) {
			return null;
		}

		strFilePath.append(context.getFilesDir() + "/" + strFileName);
		return fos;
	}

	/*
	 * 根据给定的路径和文件名获取写入的文件流，策略如下
	 * 
	 * 1、如果strSavePath为null，则直接写入到data/data/xxxx/files目录下下
	 * 2、如果是写入到SDCard目录中，则优先写入
	 * 3、如果需要写入到SDCard目录下，但是没有SDCard，则写入到/data/data/xxxx/files目录下
	 * 
	 * @param strSavePath 写入的路径
	 * 
	 * @param strFileName 写入的文件名
	 * 
	 * @param bContinue 是否追加文件
	 */
	public static FileInputStream getInputStream(Context context,
			String strSavePath, String strFileName) {

		if (strFileName == null)
			return null;

		int nIndex = strFileName.indexOf('?');
		if (nIndex != -1) {
			strFileName = strFileName.substring(0, nIndex);
			if (strFileName == null)
				return null;
		}

		FileInputStream fis = null;

		// strSavePath 为nul
		if (strSavePath == null) {
			if (context == null)
				return null;

			try {
				fis = context.openFileInput(strFileName);
			} catch (FileNotFoundException e) {
				return null;
			}

			return fis;
		}

		// 如果strSavePath不为空，则保存到指定的文件中
		try {
			fis = new FileInputStream(strSavePath + "/" + strFileName);
		} catch (FileNotFoundException e) {
			// 失败
		}
		if (fis != null)
			return fis;

		if (context == null)
			return null;

		try {
			fis = context.openFileInput(strFileName);
		} catch (FileNotFoundException e) {
			return null;
		}

		return fis;
	}
}